//
//  PlayView.m
//  JXPlayer
//
//  Created by bijan on 2016/12/13.
//  Copyright © 2016年 bijan. All rights reserved.
//

#import "JXPlayer.h"

@implementation JXPlayer

+ (instancetype)sharedPlayer{
    
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });

    return instance;
}

- (instancetype)init{
    
    if (self = [super init]) {
        
        [self addObserver];

    }
    
    return self;
}

- (void)addObserver{
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(releasePlayer:) name:RELEASE_PLAYER object:nil];
    
    
    
}

- (void)playWithUrlStr:(NSString *)urlStr playView:(UIView *)playView{
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    _playerView = playView;
    
    _asset = [AVAsset assetWithURL:url];
    
    _playerItem = [AVPlayerItem playerItemWithAsset:_asset];
    
    _player = [AVPlayer playerWithPlayerItem:_playerItem];
    
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    
    _playerLayer.frame = playView.bounds;
    
    [playView.layer addSublayer:_playerLayer];
    
    [_playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if ([keyPath isEqualToString:@"status"]) {
        
        AVPlayerItem * item = object;
        
        if (item.status == AVPlayerStatusReadyToPlay) {
            
            [_player play];
            
        }

    }
    
}


- (void)pause{
    
    [self.player pause];

    
}

- (void)close{
    
    [self.player.currentItem cancelPendingSeeks];
    [self.player.currentItem.asset cancelLoading];
    self.playerItem = nil;
    
    
}

- (void)play{
    
    [self.player play];
    
}



- (void)releasePlayer:(NSNotification*)noti{
    
    [_playerItem removeObserver:self forKeyPath:@"status"];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    self.playerItem = nil;
    
}

- (void)dealloc{
    
    NSLog(@"dealloc");
    
    
}




@end
